import os
import logging
from logging.handlers import RotatingFileHandler
from flask import Flask
from app.config import config
from app.extensions import bootstrap, db, login_manager, csrf, ckeditor, toolbar, migrate, moment
from app import cli
from app.backend import home, auth, posts, users, categorys


def create_app(config_class=None):
    if config_class is None:
        config_class = os.getenv('FLASK_CONFIG', 'development')

    app = Flask(__name__)
    app.config.from_object(config[config_class])

    cli.register(app)
    register_extensions(app)
    register_blueprints(app)

    return app


def register_extensions(app):
    bootstrap.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    csrf.init_app(app)
    ckeditor.init_app(app)
    toolbar.init_app(app)
    migrate.init_app(app, db)
    moment.init_app(app)


def register_blueprints(app):
    app.register_blueprint(home.bp)
    app.register_blueprint(auth.bp, url_prefix='/auth')
    app.register_blueprint(posts.bp, url_prefix='/posts')
    app.register_blueprint(categorys.bp, url_prefix='/categorys')
    app.register_blueprint(users.bp, url_prefix='/users')


def register_logger(app):
    app.logger.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

    file_handler = RotatingFileHandler('logs/bluelog.log', maxBytes=10 * 1024 *1024, backupCount=10)
    file_handler.setFormatter(formatter)
    file_handler.setLevel(logging.INFO)

    if not app.debug:
        app.logger.addHandler(file_handler)
